from openpyxl import load_workbook
from openpyxl.styles import PatternFill, Border, Side, Alignment, Protection, Font
wb = load_workbook("C:/TEMP/test2.xlsx")
# ws = wb.active 选择工作簿
ws = wb[wb.sheetnames[0]]
# C/D/E列合并相同单元格
x1=None
x2=None
for i in range(1,ws.max_row+1):
if x1 is None:
tv=ws.cell(row=i, column=3).value
x1=i
if tv != ws.cell(row=i+1, column=3).value:
x2=i
# print(x1,x2)
if x1 is not None and x2 is not None:
ws['C{}'.format(x1)].alignment = Alignment(horizontal='center', vertical='center')
ws.merge_cells('C{}:C{}'.format(x1,x2)) #合并单元格
ws['D{}'.format(x1)].alignment = Alignment(horizontal='center', vertical='center')
ws.merge_cells('D{}:D{}'.format(x1,x2)) #合并单元格
ws['E{}'.format(x1)].alignment = Alignment(horizontal='center', vertical='center')
ws.merge_cells('E{}:E{}'.format(x1,x2)) #合并单元格
x1=None
x2=None
Python合并Excel相同连续单元格(已排序)
最新推荐文章于 2024-09-01 11:28:27 发布